package com.jstyle.jclifexd.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.utils.StatusBarUtil;
import butterknife.BindView;
import butterknife.ButterKnife;

public class StravaWebActivity extends BaseActivity {
    @BindView(R.id.webview)
    WebView webview;
    String url = "https://www.strava.com/oauth/mobile/authorize?client_id=37590&redirect_uri=http://jstyle.jointcorp.com&response_type=code&approval_prompt=auto&scope=activity:write,read";

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_strava);
        ButterKnife.bind(this);
        StatusBarUtil.setRootViewFitsSystemWindows(this, true);
        //  StatusBarUtil.setTranslucentStatus(this);
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            StatusBarUtil.setStatusBarColor(this, 0x55000000);
        }
        if(null!=getIntent()&&null!=getIntent().getStringExtra("type")){
            ClealAll();
        }else{
            webview.loadUrl(url);
        //支持javascript
        webview.getSettings().setUserAgentString("Mozilla/5.0 (Linux; Android 4.1.1; Galaxy Nexus Build/JRO03C) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19");
        webview.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        webview.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        webview.getSettings().setBuiltInZoomControls(true);
        //扩大比例的缩放
        webview.getSettings().setUseWideViewPort(true);//让webview读取网页设置的viewport，pc版网页
        //自适应屏幕
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//适应屏幕，内容将自动缩放
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//适应内容大小
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.getSettings().setDomStorageEnabled(true);//打开DOM储存API
        webview.getSettings().setBlockNetworkImage(false);//拦截图片的加载
        webview.setInitialScale(25);//为25%，最小缩放等级
        // 设置缓存模式：不使用缓存
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 设置启动缓存
        webview.getSettings().setDefaultTextEncodingName("utf-8");
        webview.getSettings().setAppCacheEnabled(false);
        webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                webview.loadUrl(url);   //在当前的webview中跳转到新的url
                //如果不需要其他对点
                return false;
            }
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (url.startsWith("http") || url.startsWith("https")) { //http和https协议开头的执行正常的流程
                    return super.shouldInterceptRequest(view, url);
                } else {  //其他的URL则会开启一个Acitity然后去调用原生APP
                    Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(in);
                    return null;
                }
            }
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { }
            public void onPageFinished(WebView view, final String urler) {//处理网页加载成功时
                super.onPageFinished(view, urler);
            }
            //监听webview界面切换
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }
        });

        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    if (view.getUrl().contains("http://jstyle.jointcorp.com/")) {
                        Log.e("thisurl",view.getUrl());
                        Intent intent = new Intent();
                        String code=(view.getUrl().substring(0,view.getUrl().indexOf("&scope"))).replace("http://jstyle.jointcorp.com/?state=&code=", "");
                        intent.putExtra("code",code);
                        setResult(124, intent);
                        ClealAll();
                        finish();
                    } }

            }
        });

        }
        }

    /**
     * q清理网页数据
     */
    private void ClealAll(){
       //清空所有Cookie
        CookieSyncManager.createInstance(getApplicationContext());  //Create a singleton CookieSyncManager within a context
      final   CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
        cookieManager.removeSessionCookie();
        cookieManager.setAcceptCookie(true);
        StravaWebActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // TODO: 2018/3/8 清除webview缓存似乎没有用
                webview.setWebChromeClient(null);
                webview.setWebViewClient(null);
                webview.getSettings().setJavaScriptEnabled(false);
                webview.clearCache(true);//清除缓存
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                   cookieManager.removeAllCookies(null);
                    CookieManager.getInstance().flush();
                } else {
                    cookieManager.removeAllCookie();
                    CookieSyncManager.getInstance().sync();
                }
                WebStorage.getInstance().deleteAllData();
                finish();
            }
        });




        }
}
